package cn.com.fssg.platform.base.handler.impl.gsl.jc;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 工商联执委届中调整
 */
@Component
public class AdjustCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        this.auto();
        return null;
    }

    @Scheduled(cron = "0 0 3 1 1 ?")
    public void auto() {
        int year = getUPYear();
        Date start = getYearFirst(year);
        Date end = getYearLast(year);
        //查询系统管理员角色和五区角色
        String queryWxRoleSql = "select * from wx_role where role_type in ('管理员','五区角色','镇街角色')";
        List<Map<String, Object>> roleList = jdbcTemplate.queryForList(queryWxRoleSql, new HashMap<>());
        if (!CollectionUtils.isEmpty(roleList)){
            roleList.forEach(role -> {
                Map<String, Object> param = new HashMap<>();
                param.put("type", "0");
                //根据角色权限查询数据
                param.put("role_scope", role.get("id"));
                String queryWxUserSql = "select * from wx_user where type=:type and role_scope=:role_scope";
                List<Map<String, Object>> users = jdbcTemplate.queryForList(queryWxUserSql, param);
                if (users.isEmpty()) {
                    return;
                }
                List<Map<String, Object>> zw = new ArrayList<>();
                List<Map<String, Object>> userList2 = new ArrayList<>();

                users.forEach(wxUser -> {
                    Map<String, Object> zwInfo = new HashMap<>();
                    zwInfo.put("zw_id", wxUser.get("id"));
                    String queryZwInfoSql = "select * from gsl_zw_info where zw_id=:zw_id";
                    List<Map<String, Object>> zwInfos = jdbcTemplate.queryForList(queryZwInfoSql, zwInfo);
                    if (!zwInfos.isEmpty()) {
                        userList2.add(wxUser);
                        zw.add(zwInfos.get(0));
                    }
                });

                List<Map<String, Object>> newJob = userList2.stream().filter(wxUser -> (StringUtils.equals((CharSequence) wxUser.get("job_state"), "1") && ((Date)wxUser.get("create_date")).after(start) && ((Date)wxUser.get("create_date")).before(end))).collect(Collectors.toList());
                List<Map<String, Object>> quitJob = userList2.stream().filter(wxUser -> (StringUtils.equals((CharSequence) wxUser.get("job_state"), "0") && ((Date)wxUser.get("quit_date")).after(start) && ((Date)wxUser.get("quit_date")).before(end))).collect(Collectors.toList());
                Map<String, Object> gslQuitCount = new HashMap<>();
                gslQuitCount.put("id", BizUtil.cur().getSnowflakeIdStr());
                gslQuitCount.put("year", getDateString(start, "yyyy"));
                gslQuitCount.put("quit_count", String.valueOf(quitJob.size()));
                gslQuitCount.put("new_count", String.valueOf(newJob.size()));
                gslQuitCount.put("all_count", String.valueOf(userList2.size()));

                gslQuitCount.put("create_by", "1");
                gslQuitCount.put("update_by", "1");
                gslQuitCount.put("create_date", new Date());
                gslQuitCount.put("update_date", new Date());
                gslQuitCount.put("del_flag", "0");
                //根据角色权限查询数据
                String gslJcSql = "select * from gsl_jc where del_flag = '0' and role_scope=:role_scope order by create_date desc";
                Map<String, Object> gslJcParam = new HashMap<>();
                gslJcParam.put("role_scope", role.get("id"));
                List<Map<String, Object>> gslJcs = jdbcTemplate.queryForList(gslJcSql, gslJcParam);
                if (!gslJcs.isEmpty()) {
                    Map<String, Object> gslJc = gslJcs.get(0);
                    gslQuitCount.put("gsl_session", gslJc.get("session"));
                    //根据角色权限查询数据
                    gslQuitCount.put("role_scope", gslJc.get("role_scope"));
                } else {
                    return;
                }
                List<Map<String, Object>> saveLogList = new ArrayList<>();

                userList2.forEach(wxUser -> {
                    String gslJcSql1 = "select * from gsl_jc where id = :id order by create_date desc";
                    Map<String, Object> gslJcParam1 = new HashMap<>();
                    gslJcParam1.put("id", wxUser.get("gsl_session"));
                    List<Map<String, Object>> gslJc1List = jdbcTemplate.queryForList(gslJcSql1, gslJcParam1);
                    Map<String, Object> gslJc1 = new HashMap<>();
                    if(!gslJc1List.isEmpty()) {
                        gslJc1 = gslJc1List.get(0);
                    }
                    Map<String, Object> zwInfo = new HashMap<>();
                    zwInfo.put("zw_id", wxUser.get("id"));
                    Map<String, Object> zwInfos = zw.stream().filter(zwInfo1 -> StringUtils.equals((CharSequence) zwInfo1.get("zw_id"), (CharSequence) wxUser.get("id"))).findFirst().get();
                    Map<String, Object> gslQuitLog = new HashMap<>();
                    gslQuitLog.put("id", BizUtil.cur().getSnowflakeIdStr());
                    gslQuitLog.put("create_by", "1");
                    gslQuitLog.put("update_by", "1");
                    gslQuitLog.put("create_date", new Date());
                    gslQuitLog.put("update_date", new Date());
                    gslQuitLog.put("del_flag", "0");

                    //解密姓名和手机号码
                    String decName = null;
                    String phone = null;
                    try {
                        decName = decrypt((String) wxUser.get("username"), "usertokon");
                        phone = decrypt((String) zwInfos.get("phone"), "ankon");
                    } catch (Exception e) {
                        decName = (String) wxUser.get("username");
                        phone = (String) zwInfos.get("phone");
                    }

                    gslQuitLog.put("zw_name", decName);
                    gslQuitLog.put("zw_id", wxUser.get("id"));
                    gslQuitLog.put("gsl_job", zwInfos.get("gsl_post"));
                    gslQuitLog.put("phone", phone);
                    gslQuitLog.put("job", zwInfos.get("company"));
                    gslQuitLog.put("count_id", gslQuitCount.get("id"));
                    gslQuitLog.put("quit_date", wxUser.get("create_date"));
                    gslQuitLog.put("gsl_session", gslJc1.get("session"));
                    gslQuitLog.put("gsl_session_date", gslJc1.get("create_date"));
                    long qcount = quitJob.stream().filter(wx -> StringUtils.equals((CharSequence) wx.get("id"), (CharSequence) wxUser.get("id"))).count();
                    if (qcount > 0) {
                        gslQuitLog.put("user_date", wxUser.get("quit_date"));
                        gslQuitLog.put("quit_state", "0");
                        gslQuitLog.put("quit_date", wxUser.get("quit_date"));
                    } else {
                        long ncount = newJob.stream().filter(wx -> StringUtils.equals((CharSequence) wx.get("id"), (CharSequence) wxUser.get("id"))).count();
                        if (ncount > 0) {
                            gslQuitLog.put("user_date", wxUser.get("create_date"));
                            gslQuitLog.put("new_state", "1");
                            gslQuitLog.put("quit_state", "2");
                        } else {
                            gslQuitLog.put("user_date", wxUser.get("create_date"));
                            gslQuitLog.put("quit_state", "2");
                        }
                    }
                    saveLogList.add(gslQuitLog);
                });
                saveCountAndLog(gslQuitCount, saveLogList);
            });
        }
    }

    public int saveCountAndLog(Map<String, Object> gslQuitCount, List<Map<String, Object>> saveLogList) {
        int count = insertDatabase(gslQuitCount, "gsl_quit_count");
        saveLogList.forEach(item -> {
            insertDatabase(item, "gsl_quit_log");
        });
        return count;
    }

    public int insertDatabase(Map<String, Object> param, String tableName) {
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO %s (%s) VALUES (%s)",
                tableName,
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        return jdbcTemplate.update(sql, param);
    }

    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    public static Integer getUPYear() {
        SimpleDateFormat formats = new SimpleDateFormat("yyyy");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.YEAR, -1);
        Date date = c.getTime();
        return Integer.valueOf(formats.format(date));
    }

    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    public static String getDateString(Date date, String formt) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formt);
        return simpleDateFormat.format(date);
    }

    public static final String ALGORITHM = "AES";

    // 密钥补全
    public static byte[] padKey(byte[] key, int length) {
        return Arrays.copyOf(key, length);
    }

    /**
     * HEX 字符串转字节数组
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /** 解密 */
    public static String decrypt(String input, String keys) throws Exception {
        // 1. HEX 字符串 → 字节数组
        byte[] cipherBytes = hexToBytes(input);
        byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(cipherBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    }
}
